package common.loader {

	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.utils.ByteArray;
	
	import util.Logger;
	
	public class ResourceLoader extends Loader {
		
		public var info:Info;
		public var handler:Function;
		public var finish:Boolean;

		public function ResourceLoader(){
			super();
			
			finish = true;
			contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
			contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityHandler);
		}
		
		public function start(data:Info):void {
			finish = false;
			info = data;
			loadBytes(info.raw);
		}
		
		protected function completeHandler(event:Event):void {
			finish = true;
			if (handler != null) {
				info.domain = (event.target as LoaderInfo).applicationDomain;
				info.data = (event.target as LoaderInfo).content;
				handler(info);
			}
		}
		
		private function errorHandler(event:IOErrorEvent):void {Logger.error(event.toString())};
		private function securityHandler(event:SecurityErrorEvent):void {Logger.error(event.toString())};
	}
}